// import router from '@/router'
import store from '@/store'
import axios from 'axios'
import message from 'ant-design-vue/es/message'
import notification from 'ant-design-vue/es/notification'

// 创建 axios 实例
const service = axios.create({
  timeout: 20000
})

// 请求拦截器
service.interceptors.request.use(config => {
  // 带上公共token
  config.headers.common['Access-Token'] = store.getters.token
  return config
}, error => {
  return Promise.reject(error)
})

// 请求响应后处理
service.interceptors.response.use(response => {
  mockResponseHandle(response)
  if (response.status === 200) { // 成功返回
    return Promise.resolve(response.data)
  }

  // 错误处理
  responseErrorHandle(response)
  return Promise.reject(response)
}, error => {
  console.log(error)
  responseErrorHandle(error.response)
  return Promise.reject(error)
})

// 全局处理非200异常
const responseErrorHandle = function (response) {
  console.log(response)
  if (response && response.status) {
    // 根据状态码 全局处理 TO_DO
    message.error(response.status)
  } else {
    message.error('服务正在维护, 请稍后重试!')
  }
}

/**
 * mock请求处理
 * @param {Object} response
 */
const mockResponseHandle = function (response) {
  if (response && response.data && response.data._isMock) {
    notification.warning({ message: 'MOCK请求', description: response.config.url, placement: 'topRight' })
  }
}

export default service
